import express from "express";
import { addDiscuss, getAlldiscuss } from "../model/discuss.js";
import { findUserById } from '../model/user.js'

const discussRouter = express.Router()


//发布讨论
discussRouter.post('/add', async (req, res) => {
    const { userId } = req.cookies;
    const { content } = req.body

    const result = await addDiscuss(userId, content);

    res.send({
        msg: 'ok',
        data: result
    })

})


//历史消息
discussRouter.get('/getAll', async (req, res) => {
    const discusses = await getAlldiscuss()


    const getUser = async (id, item) => {
        const user = await findUserById(Number(id))
        delete user.auth;
        delete user.password;
        return { user, discuss: item }
    }
    const getdiscussessWithUser = async () => {
        let result = await Promise.all(discusses.map(async (item) => {
            return await getUser(item.userId, item)
        }))
        return result;
    }
    const discussesWithUser = await getdiscussessWithUser()
    res.send({
        msg: 'ok',
        data: discussesWithUser
    })
})


export default discussRouter